import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import Login from '../components/Login.vue'
import { useUserStore } from '../stores/userStore'

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    meta: { requiresAuth: true }
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  // 404路由处理
  {
    path: '/:pathMatch(.*)*',
    redirect: '/' // 或 component: NotFound
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL), // 推荐使用环境变量
  routes
})

// 路由守卫
router.beforeEach(async (to) => {
  const userStore = useUserStore()
  
  // 如果需要认证且用户未登录
  if (to.meta.requiresAuth && !userStore.currentUser) {
    return { name: 'login' }
  }
  
  // 如果已登录但访问的是登录页
  if (to.name === 'login' && userStore.currentUser) {
    return { name: 'home' }
  }
})

export default router